<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改商品</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 50%;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        form {
            display: flex;
            flex-direction: column;
        }
        .form-group {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        label {
            flex: 1;
            margin-right: 10px;
        }
        input, select, textarea, button {
            flex: 2;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
        }
        textarea {
            resize: none;
        }
        button {
            background-color: #4CAF50;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #45a049;
        }
        #currentImagesContainer {
            overflow-x: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 15px;
            width: 65%;
            white-space: nowrap;
        }
        .imageWrapper {
            display: inline-block;
            margin-right: 10px;
            vertical-align: top;
        }
        .imageWrapper img {
            height: 150px;
            object-fit: cover;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>修改商品</h1>
    <form id="updateProductForm" enctype="multipart/form-data">
        <div class="form-group">
            <label for="productName">商品名称:</label>
            <input type="text" id="productName" required>
        </div>
        <div class="form-group">
            <label for="productCategory">所属商品类型:</label>
            <select id="productCategory" required></select>
        </div>
        <div class="form-group">
            <label for="accessoryCategory">配件类型:</label>
            <select id="accessoryCategory" required></select>
        </div>
        <div class="form-group">
            <label for="price">价格:</label>
            <input type="number" id="price" min="0" step="0.01" required>
        </div>
        <div class="form-group">
            <label for="stock">库存:</label>
            <input type="number" id="stock" min="0" required>
        </div>
        <div class="form-group">
            <label for="images">上传图片:</label>
            <input type="file" id="images" accept="image/*" multiple>
        </div>
        <div class="form-group">
            <label>当前图片:</label>
            <div id="currentImagesContainer">
                <div id="currentImages"></div>
            </div>
        </div>
        <div class="form-group">
            <label for="description">商品描述:</label>
            <textarea id="description" rows="4" required></textarea>
        </div>
        <button type="submit">修改</button>
    </form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        const urlParams = new URLSearchParams(window.location.search);
        const productId = urlParams.get('productId');

        if (!productId) {
            alert('商品ID未提供');
            return;
        }

        function fetchProductDetails() {
            $.ajax({
                url: "/products/" + productId,
                method: "GET",
                success: function(data) {
                    $('#productName').val(data.name || '');
                    $('#price').val(data.price || '');
                    $('#stock').val(data.stock || '');
                    $('#description').val(data.detail || '');

                    fetchCategories(data.productId, data.partsId);
                    displayCurrentImages(data.iconUrl, data.subImages);
                },
                error: function(error) {
                    console.log("Error fetching product data", error);
                }
            });
        }

        function fetchCategories(selectedProductId, selectedAccessoryId) {
            $.ajax({
                url: "/product-category",
                method: "GET",
                success: function(data) {
                    const productCategorySelect = $('#productCategory');
                    const accessoryCategorySelect = $('#accessoryCategory');

                    productCategorySelect.empty();
                    accessoryCategorySelect.empty();

                    data.forEach(category => {
                        if (category.level === 0) {
                            const productOption = new Option(category.name, category.id);
                            if (selectedProductId == category.id) {
                                productOption.selected = true;
                            }
                            productCategorySelect.append(productOption);
                        }
                    });

                    productCategorySelect.on('change', function() {
                        const selectedCategoryId = $(this).val();
                        displayAccessoryCategories(selectedCategoryId, data, selectedAccessoryId);
                    });

                    if (selectedProductId) {
                        productCategorySelect.trigger('change');
                    }
                },
                error: function(error) {
                    alert('获取类型失败: ' + error.responseText);
                }
            });
        }

        function displayAccessoryCategories(parentId, categories, selectedAccessoryId) {
            const accessoryCategorySelect = $('#accessoryCategory');
            accessoryCategorySelect.empty();

            function findSubCategories(parentId) {
                return categories.filter(category => category.parentId == parentId);
            }

            function displayCategories(parentId) {
                const subCategories = findSubCategories(parentId);
                if (subCategories.length > 0) {
                    subCategories.forEach(category => {
                        if (category.level === 2) {
                            const accessoryOption = new Option(category.name, category.id);
                            if (selectedAccessoryId == category.id) {
                                accessoryOption.selected = true;
                            }
                            accessoryCategorySelect.append(accessoryOption);
                        } else {
                            displayCategories(category.id);
                        }
                    });
                }
            }
            displayCategories(parentId);
        }

        function displayCurrentImages(mainImageUrl, subImages) {
            const currentImagesDiv = $('#currentImages');
            currentImagesDiv.empty();

            if (mainImageUrl) {
                const mainImageWrapper = $('<div class="imageWrapper">');
                const mainImage = $('<img>').attr('src', mainImageUrl);
                mainImageWrapper.append(mainImage);
                currentImagesDiv.append(mainImageWrapper);
            }

            if (subImages) {
                const subImagesArray = subImages.split(',');
                subImagesArray.forEach(url => {
                    const subImageWrapper = $('<div class="imageWrapper">');
                    const subImage = $('<img>').attr('src', url.trim());
                    subImageWrapper.append(subImage);
                    currentImagesDiv.append(subImageWrapper);
                });
            }
        }

        fetchProductDetails();

        $('#updateProductForm').on('submit', function(e) {
            e.preventDefault();

            const product = {
                id: productId,
                name: $('#productName').val(),
                productId: $('#productCategory').val(),
                partsId: $('#accessoryCategory').val(),
                price: $('#price').val(),
                stock: $('#stock').val(),
                detail: $('#description').val()
            };

            const formData = new FormData();
            formData.append('product', new Blob([JSON.stringify(product)], { type: 'application/json' }));
            const images = $('#images')[0].files;
            for (let i = 0; i < images.length; i++) {
                formData.append('images', images[i]);
            }

            $.ajax({
                url: "/products/" + productId,
                method: "PATCH",
                processData: false,
                contentType: false,
                data: formData,
                success: function(data) {
                    alert('商品修改成功！');
                },
                error: function(error) {
                    alert('修改商品失败: ' + error.responseText);
                }
            });
        });
    });
</script>
</body>
</html>
